//
//  CZWheelView.m
//  A01-CZ彩票
//
//  Created by apple on 15-6-14.
//  Copyright (c) 2015年 itcast. All rights reserved.
//

#import "CZWheelView.h"
#import "UIView+Ex.h"
#import "CZWheelButton.h"
@interface CZWheelView ()


//背景图片
@property (weak, nonatomic) IBOutlet UIImageView *wheelView;

@property (nonatomic, weak) UIButton *preButton;

@property (nonatomic, strong) CADisplayLink *displayLink;
@end

@implementation CZWheelView

+ (instancetype)wheelView{
    return [[[NSBundle mainBundle] loadNibNamed:@"CZWheelView" owner:nil options:nil] lastObject];
}

//点击开始按钮  快速旋转
- (IBAction)startClick:(UIButton *)sender {
    CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    anim.toValue = @(M_PI*2*5);
    
//    anim.repeatCount = MAXFLOAT;
    anim.duration = 2;
    
    //设置动画的代理
    anim.delegate = self;
    
    [self.wheelView.layer addAnimation:anim forKey:nil];
    
}
//动画的代理方法
- (void)animationDidStart:(CAAnimation *)anim{
    //禁用和用户的交互
    self.userInteractionEnabled = NO;
    //当快速动画开始。暂停慢速动画
    self.displayLink.paused = YES;
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    self.userInteractionEnabled = YES;
    //当动画停止，让当前选中的按钮。指向最上面
    self.wheelView.transform = CGAffineTransformMakeRotation(self.preButton.tag *  -M_PI * 2/12);
    
    
    //快速动画停止以后
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.displayLink.paused = NO;
    });
}


//控制器一加载 立即慢速旋转（不能使用核心动画，使用核心动画和用户交互会有问题）
- (void)rotate{
    //和屏幕的刷新率保持一致
    CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(rotateStart)];
    self.displayLink = displayLink;
    [displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    

}

- (void)rotateStart{
    self.wheelView.transform = CGAffineTransformRotate(self.wheelView.transform, M_PI_4/60);
}

//1 生成12个按钮
- (void)awakeFromNib{
    [self rotate];  //开始慢速旋转
    int count = 12; //12个按钮
    //加载按钮上显示的图片。要分割成12份
    UIImage *bigImage = [UIImage imageNamed:@"LuckyAstrology"];
    UIImage *selBigImage = [UIImage imageNamed:@"LuckyAstrologyPressed"];
    //把pt 转换 成px （因为剪裁的时候用的cg框架，但是是px）
    CGFloat scale = [UIScreen mainScreen].scale;//@1x  @2x  @3x
    CGFloat imgW = bigImage.size.width / count * scale;
    CGFloat imgH = bigImage.size.height * scale;
    
    for (int i = 0; i < count; i++) {
        CGFloat x = i * imgW;
        CGFloat y = 0;
        //剪裁 图片 px
        CGImageRef cgImg =  CGImageCreateWithImageInRect(bigImage.CGImage, CGRectMake(x, y, imgW, imgH));
        CGImageRef cgSelImg =  CGImageCreateWithImageInRect(selBigImage.CGImage, CGRectMake(x, y, imgW, imgH));
        
        //把CGImageRef 转换成UIImage
        UIImage *img = [UIImage imageWithCGImage:cgImg];
        UIImage *selImg = [UIImage imageWithCGImage:cgSelImg];

        //释放
        CGImageRelease(cgImg);
        CGImageRelease(cgSelImg);
        //创建按钮  传过去我们想要的图片的宽度和高度（pt）
        CZWheelButton *btn = [CZWheelButton wheelButton:imgW/scale imgH:imgH/scale];
        [self.wheelView addSubview:btn];
        
        btn.tag = i;
        
        //设置按钮上显示的生肖
        [btn setImage:img forState:UIControlStateNormal];
        [btn setImage:selImg forState:UIControlStateSelected];
        
        //设置按钮选中的背景图片
        UIImage *selBackImg = [UIImage imageNamed:@"LuckyRototeSelected"];
        [btn setBackgroundImage:selBackImg forState:UIControlStateSelected];
        //设置按钮的大小
        btn.width = selBackImg.size.width;
        btn.height = selBackImg.size.height;
        
       
        //旋转图片
        btn.layer.anchorPoint = CGPointMake(0.5, 1);
         btn.center = self.wheelView.center;
//        btn.layer.position
        
        
        btn.transform = CGAffineTransformMakeRotation(i * M_PI*2/count);
        
        //点击按钮
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchDown];
        //
        self.wheelView.userInteractionEnabled = YES;
        
        //默认选中第一个按钮
        if (i == 0) {
            [self btnClick:btn];
        }
    }
}

- (void)btnClick:(UIButton *)sender{
    self.preButton.selected = NO;
    sender.selected = YES;
    
    self.preButton = sender;
}

@end
